package inf.coach.mobile;

import java.io.File;
import java.io.IOException;
import java.util.Locale;




import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;

import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class OrientationEntrance extends Activity implements OnInitListener{
private final float DISTANCE_TO_POI = 1000.0f;

//private POIList POIs;

/* location manager for position assessment */
private LocationManager locationManager;
private PositionListener locationListener;

private SensorManager sensorManager;

private static final int MY_DATA_CHECK_CODE = 0;
private TextToSpeech mTts;
private static final String TAG = "TTS";
double lat;
double lon;
Vibrator vibrator;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

	/* default */
	super.onCreate(savedInstanceState);
	super.setTitle("Funktion Seite, Bitte drehen Sie das Gerät langsam");
	setContentView(R.layout.orientation);
	locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	locationListener = new PositionListener();
	// lastLocation =
	// locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//	lastLocation = new Location("provider");
//	lastLocation.setLatitude(51.0257778f);
//	lastLocation.setLongitude(13.72263889f);	
	sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
	Intent checkIntent = new Intent();
	checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
	startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
// init button for direct access


	Bundle bundle = this.getIntent().getExtras();  
	lat = bundle.getDouble("lat");
	lon = bundle.getDouble("lon");
	System.out.println("orientation: "+lat+"/"+lon);
	vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);  
}

@Override
protected void onStart() {
	super.onStart();
	locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 100, locationListener);
	locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 100, locationListener);
	
	Sensor accelSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	sensorManager.registerListener(locationListener, accelSensor, SensorManager.SENSOR_DELAY_UI);

	Sensor magneticSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
	sensorManager.registerListener(locationListener, magneticSensor, SensorManager.SENSOR_DELAY_UI);
	
	Log.i("Sensors", "Listeners registered.");
	vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);  
	
};

@Override
protected void onStop() {
	
	if(null!=vibrator){  
        vibrator.cancel();  
    }  
	locationManager.removeUpdates(locationListener);
	locationManager.removeUpdates(locationListener);
	sensorManager.unregisterListener(locationListener);
	super.onStop();


};

@Override
protected void onDestroy() {


}



// LISTENERS


// location
private final class PositionListener implements LocationListener, SensorEventListener {

	private float[] acceleration, magnetic;
	private Location lastLocation;
	private float lastAngle = 0.0f;
	private static final int UPTATE_INTERVAL_TIME = 1000;  
	private long lastUpdateTime; 
	long[] pattern = {200, 50, 200, 50}; // OFF/ON/OFF/ON... 

		

	
	public void onLocationChanged(Location location) {
		// update last known location
		lastLocation = location;
		triggerAction();
	}

	public void onProviderDisabled(String s) {
		Toast.makeText(OrientationEntrance.this, "GPS ist aus.", Toast.LENGTH_LONG).show();
	}

	public void onProviderEnabled(String s) {
		Toast.makeText(OrientationEntrance.this, "GPS an.", Toast.LENGTH_LONG).show();
	}

	public void onStatusChanged(String s, int i, Bundle b) {
		Toast.makeText(OrientationEntrance.this, "GPS Status hat sich geändert.", Toast.LENGTH_LONG).show();
	}
	
	private void triggerAction()
	{
		  //现在检测时间  
		  long currentUpdateTime = System.currentTimeMillis();  
		  //两次检测的时间间隔  
		  long timeInterval = currentUpdateTime - lastUpdateTime;    
		  //判断是否达到了检测时间间隔  
		  if(timeInterval < UPTATE_INTERVAL_TIME)   
		   return;  
		  //现在的时间变成last时间  
		  lastUpdateTime = currentUpdateTime; 
		  
		if ((null == lastLocation) || (0.0f == lastAngle)) return;
		// test if POI is within reach
		//		POI nearestPOI = null;
			Location poiLocation = new Location(lastLocation);
			float minDist = DISTANCE_TO_POI;
			float dist, angle;	
			poiLocation.setLatitude(lat);
			poiLocation.setLongitude(lon);
			dist = lastLocation.distanceTo(poiLocation);
			angle = lastLocation.bearingTo(poiLocation);
			
			if ((30 >= Math.abs(lastAngle-angle)) )
			{
	             vibrator.vibrate(pattern, -1);//-1不重复，非-1为从pattern的指定下标开始重复  
			}
			
			
	}

	public void onAccuracyChanged(Sensor arg0, int arg1) {
		
		
	}

	public void onSensorChanged(SensorEvent arg0) {
		if (Sensor.TYPE_ACCELEROMETER == arg0.sensor.getType())
		{
			acceleration = arg0.values;
		}
		else if (Sensor.TYPE_MAGNETIC_FIELD == arg0.sensor.getType())
		{
			magnetic = arg0.values;
		}
		
		float[] rotMatrix = new float[9];
		
		if ((null != acceleration) && (null != magnetic))
		{
			if (SensorManager.getRotationMatrix(rotMatrix, null, acceleration, magnetic))
			{
				float orientation[] = new float[3];
				SensorManager.getOrientation(rotMatrix, orientation);
				lastAngle = orientation[0] * 180.0f/(float)Math.PI;
				//Log.i("Sensors", Float.toString(lastAngle));
			}
			
			triggerAction();
		}
	}

}


public void onInit(int status) {
	// TODO Auto-generated method stub
	if (status == TextToSpeech.SUCCESS) {
		int result = mTts.setLanguage(Locale.US);
		// 设置发音语言
		if (result == TextToSpeech.LANG_MISSING_DATA
				|| result == TextToSpeech.LANG_NOT_SUPPORTED)
		// 判断语言是否可用
		{
			Log.v(TAG, "Language is not available");
			message.show(OrientationEntrance.this, "Error",
					"Language is not available, please set it at Setting!");

		} else {
			//Toast.makeText(Orientation.this, "TTS started.", Toast.LENGTH_LONG).show();
		}
	}

}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	if (requestCode == MY_DATA_CHECK_CODE) {
		if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
			// success, create the TTS instance
			mTts = new TextToSpeech(this,this);
		} else {
			// missing data, install it
			Intent installIntent = new Intent();
			installIntent
					.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
			startActivity(installIntent);
		}
	}
}

public boolean onKeyDown(int keyCode, KeyEvent event) {  
    if(keyCode== KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){  
  
        System.out.println("---------------onKeyDown---------------");    
        mTts.shutdown();
        OrientationEntrance.this.finish(); 
         return true; //确认返回了  
    }  
    return false;  //不允许返回  
}

protected void dialoggoback() { 
    AlertDialog.Builder builder = new Builder(OrientationEntrance.this); 
    builder.setMessage("Möchten Sie zur letzten Seite zurück springen?"); 
    builder.setTitle("Information"); 
    builder.setPositiveButton("ok", 
            new android.content.DialogInterface.OnClickListener() { 
                @Override 
                public void onClick(DialogInterface dialog, int which) { 
                    dialog.dismiss(); 
                    mTts.shutdown();
                    OrientationEntrance.this.finish(); 
                }

            }); 
    builder.setNegativeButton("abbrechen", 
            new android.content.DialogInterface.OnClickListener() { 
                @Override 
                public void onClick(DialogInterface dialog, int which) { 
                    dialog.dismiss(); 
                } 
            }); 
    builder.create().show(); 
} 

}

